<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0px;
        padding: 0px;
      }
      .container {
        display: flex;
        width: 100%;
      }
      .left {
        width: 200px;
        background: pink;
        order: 1;
      }
      .center {
        flex: 1;
        background: blanchedalmond;
        order: 2;
      }
      .right {
        width: 200px;
        background: cadetblue;
        order: 3;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="row center">第二列</div>
      <div class="row left">第一列</div>
      <div class="row right">第三列</div>
    </div>
    <script>
      let arr = [
        { id: 1, name: "部门1", pid: 0 },
        { id: 2, name: "部门2", pid: 1 },
        { id: 3, name: "部门3", pid: 1 },
        { id: 4, name: "部门4", pid: 3 },
        { id: 5, name: "部门5", pid: 4 },
      ];
      function flatTotree(arr) {
        let trees = [];
        let map = {}
        // 之前使用的是遍历加递归
        // 优化：使用hash表和遍历
        // for(var item of arr) {
        //   map[item.id] = {...item, children: []}
        // }
        // for(var item of arr) {
        //   let id = item.id
        //   let pid = item.pid
        //   let newItem = map[id]
        //   if(pid === 0) {
        //     trees.push(newItem)
        //   }else {
        //     if(!map[pid]) {
        //       map[pid] = { 
        //         children: []
        //       }
        //     }
        //     // 利用引用传递
        //     map[pid].children.push(newItem)
        //   }
        // }
          for(var item of arr) {
            let id = item.id
            let pid = item.pid
            map[id] = {...item,children: []}
            if(pid === 0) {
              trees.push(map[id])
            }else {
              map[pid].children.push(map[id])
            }
          }
        return trees
      }
      console.log(flatTotree(arr));
    </script>
  </body>
</html>
